# -*- coding: utf-8 -*-
from datetime import datetime as pydatetime
from base64 import b64encode
import hmac
import hashlib

import requests

from config import (ALLOWED_EXTENSIONS,
                    ISBN_SID,
                    ISBN_SKEY)


def get_isbn_info(isbn):
    datetime = pydatetime.utcnow().strftime(r"%a, %d %b %Y %H:%M:%S GMT")
    sign_str = f"x-date: {datetime}\nx-source: market"
    sign = b64encode(hmac.new(ISBN_SKEY.encode("utf-8"), sign_str.encode("utf-8"), hashlib.sha1).digest())
    auth = f'hmac id="{ISBN_SID}", algorithm="hmac-sha1", headers="x-date x-source", signature="{sign.decode("utf-8")}"'
    return requests.get(
        url="https://service-osj3eufj-1255468759.ap-shanghai.apigateway.myqcloud.com/release/isbn",
        params={"isbn": isbn},
        headers={
            "X-Source": "market",
            "X-Date": datetime,
            "Authorization": auth}).json()


def allowed_file(filename):
    return "." in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
